package com.ruoyi.web.controller.common;

import com.axzhengxin.platform.common.enums.RedisKey;
import com.axzhengxin.platform.common.util.SmsSendService;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    // 验证码类型
    @Value("${ruoyi.captchaType}")
    private String captchaType;


    @Autowired
    private SmsSendService smsSendService;

    @Autowired
    private ISysUserService userService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    /**
     * 忘记密码-》修改密码
     *
     * @param userName           用户名
     * @param newPassword        新密码
     * @param confirmNewPassword 确认新密码
     * @param phone              手机号
     * @param code               验证码
     * @return 结果集
     */
    @Log(title = "忘记密码", businessType = BusinessType.UPDATE)
    @PostMapping("/forgetPSW")
    public AjaxResult forgetPSW(String userName, String newPassword, String confirmNewPassword, String phone, String code) {
        //1.判断用户名是否存在，用户名是否和手机号对应
        SysUser sysUser = userService.selectUserByUserName(userName);
        if (sysUser == null) {
            return AjaxResult.error("您填写的登录用户名不存在，请核验！");
        }
        //2.确认新旧密码是否一直
        if (!confirmNewPassword.equals(newPassword)) {
            return AjaxResult.error("新旧密码不一致!请重新填写");
        }
        //3.判断手机号是否匹配，判断验证码的有效性
        String phonenumber = sysUser.getPhonenumber();
        if (!phonenumber.equals(phone)) {
            return AjaxResult.error("手机号与用户不匹配，请使用系统预留手机号！");
        }
        //从redis中查询手机验证码并进行校验
        String redisPhoneCode = redisCache.getCacheObject(RedisKey.PHONE_NUMBER_CODE + phone.trim());
        if (StringUtils.isEmpty(redisPhoneCode) || !redisPhoneCode.equals(code)) {
            return AjaxResult.error("验证码有误或已过期！");
        }
        //4.对新密码进行加密，进行密码修改操作
        String password = SecurityUtils.encryptPassword(userName, newPassword);
        userService.resetUserPwd(userName, password);
        return AjaxResult.success();
    }


    /**
     * 获取手机验证码
     *
     * @param phone 手机号
     * @return
     */
    @Log(title = "获取修改密码的手机验证码")
    @PostMapping("/getPhoneCode")
    public AjaxResult getPhoneCode(String phone) {
        AjaxResult ajax = AjaxResult.success();
        try {
            //1.生成验证码，并发送短信
            String code = SmsSendService.randomCode(5);
            /*String code="12345";*/
            redisCache.setCacheObject(RedisKey.PHONE_NUMBER_CODE + phone.trim(), code, 1, TimeUnit.MINUTES);
            String resultCode = smsSendService.sendMsg("prod", phone, null, "您正在执行找回密码操作，你的验证码是" + code + ",有效期一分钟，请妥善保管！", "412607");
            //2.将验证码和手机号绑定 存入redis中，设置一分钟的有效时间
            /*if ("0".equals(resultCode)) {*/
            log.info(code + "----------------------------");
            /*}*/
            return AjaxResult.success("验证码获取成功，请查收！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("获取验证码失败");
    }
}
